package com.graduate.twentyone.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import io.swagger.annotations.Api;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.UUID;
@Controller
@RequestMapping("/upload")
@ResponseBody
@Api(value = "UploadController管理", tags = "UploadController管理接口API")
public class UploadConfig {

    private String userBucketName = "2021canyin";
    // Endpoint以杭州为例，其它Region请按实际情况填写。
    private String endpoint = "oss-cn-shanghai.aliyuncs.com";
    // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，
    // 创建并使用RAM子账号进行API访问或日常运维，
    // 请登录 https://ram.console.aliyun.com 创建。
    private String accessKeyId = "LTAI5tGAA6tNp4p5umgYB2tR";
    private String accessKeySecret = "ZJZDpY08Iz7u7SgWNRBc3FEm2XqbH0";

    private String filepath = "";

    @PostMapping("/goodsimg")
    public String upLoadFoodsImag(@RequestParam("file") MultipartFile file) {
        try {
            String filename = file.getOriginalFilename();
            InputStream in = file.getInputStream();
            String uu = UUID.randomUUID().toString().substring(0,6);
            filepath = "canyin/" + uu + filename;
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //ossClient.putObject("<yourBucketName>", "<yourObjectName>", inputStream);
            ossClient.putObject(userBucketName, filepath, in);
            // 关闭OSSClient。
            ossClient.shutdown();
            //https://guimeigroup3.oss-cn-beijing.aliyuncs.com/5cd19074e7bce75dca87bf9a.jpg
            String path = "https://" + userBucketName + "." + endpoint + "/" + filepath;
            System.out.println("Success--Path::" + path);
            return path;
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }
}
